# coding=utf-8
"""
    @Author：SimpleTree
    @date：2025/4/28 20:21
    @desc: 
"""
import base64
import json
import logging
import os.path
import time
import uuid

from api import settings
from api.db.services.canvas_service import CanvasTemplateService
from api.utils.file_utils import get_project_base_directory


def encode_to_base64(input_string):
    base64_encoded = base64.b64encode(input_string.encode('utf-8'))
    return base64_encoded.decode('utf-8')


def init_superuser():
    # user_info = {
    #     "id": uuid.uuid1().hex,
    #     "password": encode_to_base64("admin"),
    #     "nickname": "admin",
    #     "is_superuser": True,
    #     "email": "admin@ragflow.io",
    #     "creator": "system",
    #     "status": "1",
    # }
    # tenant = {
    #     "id": user_info["id"],
    #     "name": user_info["nickname"] + "‘s Kingdom",
    #     "llm_id": settings.CHAT_MDL,
    #     "embd_id": settings.EMBEDDING_MDL,
    #     "asr_id": settings.ASR_MDL,
    #     "parser_ids": settings.PARSERS,
    #     "img2txt_id": settings.IMAGE2TEXT_MDL
    # }
    # user_tenant = {
    #     "tenant_id": user_info["id"],
    #     "user_id": user_info["id"],
    #     "invited_by": user_info["id"],
    #     "role": UserTenantRole.OWNER
    # }
    # tenant_llm = []
    # for llm in LLMService.query(fid=settings.LLM_FACTORY):
    #     tenant_llm.append(
    #         {"tenant_id": user_info["id"], "llm_factory": settings.LLM_FACTORY,
    #          "llm_name": llm.llm_name, "model_type": llm.model_type,
    #          "api_key": settings.API_KEY, "api_base": settings.LLM_BASE_URL})
    #
    # if not UserService.save(**user_info):
    #     logging.error("can't init admin.")
    #     return
    # TenantService.insert(**tenant)
    # UserTenantService.insert(**user_tenant)
    # TenantLLMService.insert_many(tenant_llm)
    # logging.info(
    #     "Super user initialized. email: admin@ragflow.io, password: admin. Changing the password after login is strongly recommended.")
    #
    # chat_mdl = LLMBundle(tenant["id"], LLMType.CHAT, tenant["llm_id"])
    # msg = chat_mdl.chat(system="", history=[
    #     {"role": "user", "content": "Hello!"}], gen_conf={})
    # if msg.find("ERROR: ") == 0:
    #     logging.error(
    #         "'{}' doesn't work. {}".format(
    #             tenant["llm_id"],msg
    #         )
    #     )
    # embd_mdl = LLMBundle(tenant["id"], LLMType.EMBEDDING, tenant["embd_id"])
    # v, c = embd_mdl.encode(["Hello!"])
    # if c == 0:
    #     logging.error(
    #         "'{}' doesn't work!".format(tenant["embd_id"])
    #     )
    pass


def init_llm_factory():
    # try:
    #     LLMService.filter_delete([(LLM.fid == "MiniMax" or LLM.fid == "Minimax")])
    #     LLMService.filter_delete([(LLM.fid == "cohere")])
    #     LLMFactoriesService.filter_delete([LLMFactories.name == "cohere"])
    # except Exception:
    #     pass
    pass


def add_graph_templates():
    dir = os.path.join(get_project_base_directory(), "agent", "templates")
    for fnm in os.listdir(dir):
        try:
            cnvs = json.load(open(os.path.join(dir, fnm), "r", encoding="utf-8"))
            try:
                CanvasTemplateService.save(**cnvs)
            except Exception:
                CanvasTemplateService.update_by_id(cnvs["id"], cnvs)
        except Exception:
            logging.exception("Add graph templates error: ")


def init_web_data():
    start_time = time.time()

    init_llm_factory()
    # if not UserService.get_all().count()
    # init_superuser()

    add_graph_templates()
    logging.info("init web data success:{}".format(time.time() - start_time))